package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetOrganizationResponse;
import com.woyao.core.model.InterestSummary;
import com.woyao.core.model.MediaSummary;
import com.woyao.core.model.NewItemSummary;
import com.woyao.core.model.Organization;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.CollectionUtil;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class OrgViewActivity extends AppCompatActivity {

    private Button shareBtn;
    private Button applyBtn;
    private FrameLayout mainView;

    private  Integer id;
    private Organization current = new Organization();

    private ClipboardManager myClipboard;
    private ClipData myClip;

    private TextView descTxt;
    private ImageView imageImg;
    private TextView titleTxt;

    private LinearLayout attrsInfo;
    private LinearLayout membersInfo;
    private LinearLayout partnersInfo;
    private LinearLayout demandsInfo;
    private LinearLayout updatesInfo;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.org_view);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        mainView = (FrameLayout) findViewById(R.id.main_view);
        titleTxt = (TextView) findViewById(R.id.person_title);

        descTxt = (TextView) findViewById(R.id.person_desc);
        imageImg = (ImageView) findViewById(R.id.person_image);


        attrsInfo = (LinearLayout) findViewById(R.id.person_attrs);
        membersInfo = (LinearLayout) findViewById(R.id.person_members);
        partnersInfo = (LinearLayout) findViewById(R.id.person_partners);
        demandsInfo = (LinearLayout) findViewById(R.id.person_demands);
        updatesInfo = (LinearLayout) findViewById(R.id.updates_info);

        shareBtn = (Button)findViewById(R.id.sharelink);

        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                displayReferContent();
            }
        });


        applyBtn = (Button)findViewById(R.id.org_apply);
        applyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Dialog alertDialog = new AlertDialog.Builder(OrgViewActivity.this).
                        setTitle("提示").
                        setMessage("申请加入吗？").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                applyOrgNow();
                            }
                        }).
                        setNegativeButton("取消", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).
                        create();
                alertDialog.show();

            }
        });

        TextView footerText = (TextView) findViewById(R.id.slogan);
        footerText.setText(footerText.getText() + " " + Common.getCurrentVersion(OrgViewActivity.this));


        Intent intent = getIntent();
        id = intent.getIntExtra("id",0);

        mainView.setVisibility(View.INVISIBLE);
        loadData();


    }




    private void displayReferContent() {
        final String text = "Http://www.woyaooo.com/o/" + id + "?rid=" + userId;

        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("分享").
                setMessage(text).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                        myClip = ClipData.newPlainText("text", text);
                        myClipboard.setPrimaryClip(myClip);
                    }
                }).
                create();
        alertDialog.show();
    }


    private  void applyOrgNow(){





        AsyncTask<Void,Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<BaseResponse> responseCall = svc.applyOrg(userId,current.getId());
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        progressDialog.dismiss();
                        if ( response.isSuccess()){
                            Common.alert(OrgViewActivity.this,response.getMessage());
                        }else{
                            Dialog alertDialog = new AlertDialog.Builder(OrgViewActivity.this).
                                    setTitle("信息").
                                    setMessage(response.getMessage()).
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (response.getCondition()) {
                                                case "verify":
                                                    renderVerify();
                                                    break;
                                                case "charge":
                                                    renderMoney();
                                                    break;

                                                default:
                                            }
                                        }
                                    }).
                                    setPositiveButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    }).
                                    create();
                            alertDialog.show();
                        }
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();

    }

    private void renderMoney( ){
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(OrgViewActivity.this, MoneyActivity.class);
        startActivity(intent);
    }
    public void renderVerify(){
        Intent intent = new Intent();
        intent.setClass(OrgViewActivity.this, VerifyActivity.class);
        startActivity(intent);
    }



//    @Override
//    public void onBackPressed() {
//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        if (drawer.isDrawerOpen(GravityCompat.START)) {
//            drawer.closeDrawer(GravityCompat.START);
//        } else {
//            super.onBackPressed();
//        }
//    }



    private void loadData() {


        progressDialog = new ProgressDialog(OrgViewActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("加载···");
        progressDialog.show();

        AsyncTask<Void, Void, GetOrganizationResponse> task = new AsyncTask<Void, Void, GetOrganizationResponse>() {
            @Override
            protected GetOrganizationResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetOrganizationResponse> responseCall = svc.getOrganization(userId, id);
                GetOrganizationResponse ret = null;
                try {
                    ret = responseCall.execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = null;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final GetOrganizationResponse resp) {
                if (resp != null) {
                    if (resp.isSuccess()) {
                        current = resp.getContent();
                        render();
                    } else {
                       Common.alert(OrgViewActivity.this,resp.getMessage());
                    }
                } else {
                    Common.alert(OrgViewActivity.this,"请检查网络后重试！");
                }

                progressDialog.dismiss();

            }

            @Override
            protected void onCancelled() {

                progressDialog.dismiss();
                Common.alert(OrgViewActivity.this,"请检查网络后重试！");

            }
        };
        task.execute((Void) null);

    }


    private void render() {

        this.setTitle( current.getTitle());

        if (current.getAppliable()){
            applyBtn.setVisibility(View.VISIBLE);
        }else{
            applyBtn.setVisibility(View.GONE);
        }


        titleTxt.setText(current.getTitle());

        if (StringUtil.notNullOrEmpty(current.getImage())) {
            Picasso.with(this)
                    .load(current.getImage())
                    .into(imageImg);
        } else {
            imageImg.setImageResource(R.drawable.no_avartar);
        }

        descTxt.setText(current.getDescription());



        displayAttrs();

        displayMembers();

        displayPartners();

        displayDemands();
        displayUpdates();

        if (!current.getCurrent()){
            applyBtn.setVisibility(View.VISIBLE);
        }else{
            applyBtn.setVisibility(View.GONE);
        }

        mainView.setVisibility(View.VISIBLE);
    }

    private void voteIt( final Integer uid,final String act ) {

        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {

                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);

                        Call<BaseResponse> responseCall = svc.addVote(userId, uid,act);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        if ( response == null || response.isSuccess() == false) {
                            Common.showSnack(OrgViewActivity.this, shareBtn,"抱歉,处理失败，请重试。");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        Common.showSnack(OrgViewActivity.this, shareBtn,"抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }
    private void displayUpdates() {

        updatesInfo.removeAllViews();

        if (current.getMoves().size() == 0)
            return;

        if (!current.getMoves_summary().equals("")) {

            LinearLayout item1 = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getMoves_summary());
            updatesInfo.addView(item1);
        }


        if (CollectionUtil.notEmpty(current.getMoves())) {
            //合作的人
            Integer order = 0;
            for (final InterestSummary interest : current.getMoves()) {
                order  = order  + 1;
                LinearLayout item = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.move_item, null);

                final TextView move_order = (TextView) item.findViewById(R.id.move_order);
                final TextView move_subject = (TextView) item.findViewById(R.id.move_subject);
                final TextView move_desc = (TextView) item.findViewById(R.id.move_desc);
                final TextView move_created = (TextView) item.findViewById(R.id.move_created);
                final TextView yes_dig_num = (TextView) item.findViewById(R.id.yes_dig_num);
                final TextView no_dig_num = (TextView) item.findViewById(R.id.no_dig_num);
                final LinearLayout mediaItems = (LinearLayout) item.findViewById(R.id.id_move_medias);
                final ImageView voteUp = (ImageView) item.findViewById(R.id.yesdig);
                final ImageView voteDown = (ImageView) item.findViewById(R.id.nodig);

                final TextView move_displayname = (TextView) item.findViewById(R.id.move_displayname);
                final CircleImageView move_avatar = (CircleImageView) item.findViewById(R.id.move_avatar);

                final LinearLayout moveItem = (LinearLayout) item.findViewById(R.id.moveItem);
                final TextView move_title = (TextView) item.findViewById(R.id.move_title);
                move_title.setText( interest.getTitle());

                moveItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (interest.getRelation_type().equals("demand")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getRelation_id());
                            intent.setClass(OrgViewActivity.this, ChanceViewActivity.class);
                            startActivity(intent);
                        }

                        if (interest.getRelation_type().equals("org")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getRelation_id());
                            intent.setClass(OrgViewActivity.this, OrgViewActivity.class);
                            startActivity(intent);
                        }

                        if (interest.getRelation_type().equals("person")) {
                            Intent intent = new Intent();
                            intent.putExtra("id", interest.getUser_id());
                            intent.setClass(OrgViewActivity.this, PersonViewActivity.class);
                            startActivity(intent);
                        }
                    }
                });


                move_displayname.setText(interest.getDisplayname());

                if (StringUtil.notNullOrEmpty(interest.getSnailview())) {
                    Picasso.with(OrgViewActivity.this)
                            .load(interest.getSnailview())
                            .into(move_avatar);
                } else {
                    move_avatar.setImageResource(R.drawable.no_avartar);
                }

                move_avatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getUser_id());
                        intent.setClass(OrgViewActivity.this, PersonViewActivity.class);
                        startActivity(intent);
                    }
                });

                move_order.setText( order  + "" );
                voteUp.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        yes_dig_num.setText( interest.getPositive() + 1 +"");
                        voteIt( interest.getId(), "up");
                        voteUp.setImageResource(R.drawable.vote_up_grey);
                        voteDown.setImageResource(R.drawable.vote_down_grey);
                    }
                });

                voteDown.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        no_dig_num.setText( interest.getNegative() + 1 +"");
                        voteIt( interest.getId(), "down");
                        voteUp.setImageResource(R.drawable.vote_up_grey);
                        voteDown.setImageResource(R.drawable.vote_down_grey);
                    }
                });

                if  (interest.getVoted()){
                    voteUp.setImageResource(R.drawable.vote_up_grey);
                    voteDown.setImageResource(R.drawable.vote_down_grey);
                }
                move_desc.setText(interest.getDescription());
                move_created.setText(interest.getCreated());
                yes_dig_num.setText(interest.getPositive() +"");
                no_dig_num.setText(interest.getNegative() +"");

                String tempstr = "";
                for (String onestr : interest.getSubject()){
                    tempstr += "#" + onestr +" ";
                }
                move_subject.setText( tempstr ) ;

                for (final MediaSummary ms : interest.getMedias()) {
                    android.support.v7.widget.ContentFrameLayout image_item = (android.support.v7.widget.ContentFrameLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.media_item, null);
                    ImageView imageView = (ImageView) image_item.findViewById(R.id.media_pic);
                    final Button deleteBtn = (Button)image_item.findViewById(R.id.media_delete);
                    final Button playBtn = (Button)image_item.findViewById(R.id.media_play);

                    if (ms.getId().endsWith("mp4")){
                        playBtn.setVisibility(View.VISIBLE);
                    }else{
                        playBtn.setVisibility(View.GONE);
                    }

                    deleteBtn.setVisibility(View.GONE);

                    if (StringUtil.notNullOrEmpty(ms.getSnailview())) {
                        Picasso.with(OrgViewActivity.this)
                                .load(ms.getSnailview())
                                .into(imageView);
                    } else {
                        imageView.setImageResource(R.drawable.no_avartar);
                    }

                    mediaItems.addView(image_item);

                }

                updatesInfo.addView(item);

            }
            View splitter = (View) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.splitter, null);
            updatesInfo.addView(splitter);
        }


    }
    private void displayAttrs() {

        attrsInfo.removeAllViews();



        for  ( Map<String,String> oneMap : current.getAttrs()) {
            for (Map.Entry<String, String> entry : oneMap.entrySet()){
                LinearLayout item = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.list_item, null);

                TextView title = (TextView) item.findViewById(R.id.title);
                TextView text = (TextView) item.findViewById(R.id.text);
                title.setText(entry.getKey() + ":");
                text.setText(entry.getValue());
                attrsInfo.addView(item);
            }
        }

        if (current.getAttrs().size() >0 ) {
            View splitter = (View) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.splitter, null);
            attrsInfo.addView(splitter);
        }

    }

    private void displayMembers() {

        membersInfo.removeAllViews();

        if (! current.getMembers_summary().equals("")) {
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getMembers_summary());
            membersInfo.addView(item1);
        }

        for (final NewItemSummary oneItem : current.getMembers()) {
            LinearLayout item = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.partner_item, null);
            CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);

            TextView title = (TextView) item.findViewById(R.id.partner_title);
            final TextView desc = (TextView) item.findViewById(R.id.partner_desc);

            title.setText( oneItem.getTitle());
            desc.setText(oneItem.getDescription());


            if (StringUtil.notNullOrEmpty(oneItem.getImage())) {
                Picasso.with(this)
                        .load(oneItem.getImage())
                        .into(avatar);
            } else {
                avatar.setImageResource(R.drawable.no_avartar);
            }

            avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("id",oneItem.getId() );
                    intent.setClass(OrgViewActivity.this, OrgViewActivity.class);
                    startActivity(intent);
                }
            });

            membersInfo.addView(item);
        }

        if (current.getMembers().size() >0 ) {
            View splitter = (View) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.splitter, null);
            membersInfo.addView(splitter);
        }

    }

    private void displayPartners() {

        partnersInfo.removeAllViews();

        if (! current.getPartners_summary().equals("")) {
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getPartners_summary());
            partnersInfo.addView(item1);
        }

        for (final NewItemSummary oneItem : current.getPartners()) {
            LinearLayout item = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.partner_item, null);
            CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);

            final TextView title = (TextView) item.findViewById(R.id.partner_title);
            final TextView desc = (TextView) item.findViewById(R.id.partner_desc);

            title.setText( oneItem.getTitle());
            desc.setText(oneItem.getDescription());


            if (StringUtil.notNullOrEmpty(oneItem.getImage())) {
                Picasso.with(this)
                        .load(oneItem.getImage())
                        .into(avatar);
            } else {
                avatar.setImageResource(R.drawable.no_avartar);
            }

            avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("id",oneItem.getId() );
                    intent.setClass(OrgViewActivity.this, OrgViewActivity.class);
                    startActivity(intent);
                }
            });

            partnersInfo.addView(item);
        }

        if (current.getPartners().size() >0 ) {
            View splitter = (View) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.splitter, null);
            partnersInfo.addView(splitter);
        }


    }


    private void displayDemands() {

        demandsInfo.removeAllViews();
        if (! current.getDemands_summary().equals("")) {
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);

            title1.setText(current.getDemands_summary());
            demandsInfo.addView(item1);
        }

        for (final NewItemSummary oneItem : current.getDemands()) {
            LinearLayout item = (LinearLayout) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.partner_item, null);
            CircleImageView avatar = (CircleImageView) item.findViewById(R.id.partner_avatar);

            TextView title = (TextView) item.findViewById(R.id.partner_title);
            final TextView desc = (TextView) item.findViewById(R.id.partner_desc);

            title.setText( oneItem.getTitle());
            desc.setText(oneItem.getDescription());


            if (StringUtil.notNullOrEmpty(oneItem.getImage())) {
                Picasso.with(this)
                        .load(oneItem.getImage())
                        .into(avatar);
            } else {
                avatar.setImageResource(R.drawable.no_avartar);
            }

            avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent();
                    intent.putExtra("id",oneItem.getId() );
                    intent.setClass(OrgViewActivity.this, ChanceViewActivity.class);
                    startActivity(intent);
                }
            });

            demandsInfo.addView(item);
        }

        if (current.getDemands().size() >0 ) {
            View splitter = (View) LayoutInflater.from(OrgViewActivity.this).inflate(R.layout.splitter, null);
            demandsInfo.addView(splitter);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);



    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }
}
